//
//  DetailController.m
//  Cook
//
//  Created by 0.0 on 15-4-21.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//
//  选集按钮+100
//  材料按钮+1000

#import "DetailController.h"
#import "VegetableMenu.h"
#import "UMSocial.h"
#import "VegetableDetail.h"
#import "MaterialTableViewCell.h"
#import "CookMethodTableViewCell.h"
#import "DMtril.h"
#import "CookMethod.h"
#import "TableHeaderlButton.h"
#import "DMView.h"
#import "DownLoad.h"
#import "FavoriteModel.h"
#import "MONActivityIndicatorView.h"
#import "FavoriteDataBase.h"
#import "MyMoviePlayerController.h"
#import "DetailMoviePlayer.h"

#define headerViewHigth 60
#define buttonViewHigth 60

@interface DetailController () <UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate, MONActivityIndicatorViewDelegate, UIAlertViewDelegate>
{
    UIView *_tableHeaderView; // 定义tableView的headerView
    UITableView *_tableView; // 定义tableView
    UIAlertView *_favoriteView; // 收藏提示view
    
    
//    NSTimer *_fileTimer; // 加载失败计时器
    UIAlertView *_fileAlertView; //  加载失败提示view
    
    NSTimer *_favoriteTimer; // 收藏提示view计时器
}

@property (nonatomic, retain) NSMutableArray *videoArray; // 视频播放列表数组
@property (nonatomic, retain) VegetableDetail *detailModel; // 菜品详情做法model
@property (nonatomic, retain) NSMutableArray *tableArray; // 存放往tableViewCell中填充数据的数组
@property (nonatomic, retain) NSMutableArray *materialArray; // 材料数组
@property (nonatomic, retain) NSMutableArray *knowArray; // 常识数组
@property (nonatomic, retain) NSArray *dButtonArray; // 存放四个按钮上图片和文字名字的数组
@property (nonatomic, retain) NSMutableArray *dBArray; // 存放四个按钮的数组

@property (nonatomic, retain) UIView *sectionView; // sectionVIew
@property (nonatomic, retain) UIView *frontView; // 加载视图(加载时候盖在最上面)
@property (nonatomic, retain) UIBarButtonItem *favoriteBar; // 收藏按钮

@property (nonatomic, retain) UIImage *favoriteImage; // 未收藏的按钮的图片
@property (nonatomic, retain) UIImage *favoriteImage2; // 已收藏的按钮的图片

@property (nonatomic, retain)  NSTimer *netTimer; // 加载计时器

@end

@implementation DetailController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_vegetableMenuModel release];
    [_moviePlayer release];
    [_vegetableBackImage release];
    [_playButton release];
    [_videoArray release];
    [_detailModel release];
    [_tableArray release];
    [_materialArray release];
    [_knowArray release];
    [_dButtonArray release];
    [_dBArray release];
    [_sectionView release];
    [_frontView release];
    [_favoriteBar release];
    [_favoriteImage release];
    [_favoriteImage2 release];
    [_netTimer release];
    

  
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.detailModel = [[[VegetableDetail alloc] init] autorelease];
        self.vegetableMenuModel = [[[VegetableMenu alloc] init] autorelease];
        self.videoArray = [NSMutableArray array];
        self.materialArray = [NSMutableArray array];
        self.tableArray = [NSMutableArray array];
        self.knowArray = [NSMutableArray array];
        
        self.dButtonArray = @[@{@"imageName":@"material", @"name":@"材料"}, @{@"imageName":@"cookMethod", @"name":@"做法"}, @{@"imageName":@"knowledge", @"name":@"常识"}, @{@"imageName":@"download", @"name":@"下载"}];
        
        self.dBArray = [NSMutableArray array];
       
    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // 准备好, 创建收藏按钮的图片
    [self createFavoriteButtonImage];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self createNavBar];
    [self viewWillCome];
    [self createIndicator];
}




#pragma mark - 创建小菊花
- (void)createIndicator
{
    self.frontView = [[UIView alloc] initWithFrame:self.view.frame];
    _frontView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5f];
    [self.view addSubview:_frontView];
    [_frontView release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"frontView" object:nil];
    
    MONActivityIndicatorView *indicator = [[MONActivityIndicatorView alloc] init];
    indicator.delegate = self;
    indicator.numberOfCircles = 3;
    indicator.radius = 20;
    indicator.internalSpacing = 3;
    indicator.center = _frontView.center;
   
    // 隐藏顶部navigationbar
    self.navigationController.navigationBar.hidden = YES;
    
    [indicator startAnimating];
    [_frontView addSubview:indicator];
    [indicator release];
    
    self.netTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(isHaveFront) userInfo:nil repeats:NO];
}

// 数据加载成功通知
- (void)notification:(NSNotificationCenter *)nofi
{
    [_netTimer invalidate];
    self.navigationController.navigationBar.hidden = NO;
    [self.frontView removeFromSuperview];
    self.frontView = nil;
    
}

// 判断加载情况
- (void)isHaveFront
{
    if (_frontView != nil) {
        _fileAlertView = [[UIAlertView alloc] initWithTitle:@"加载失败" message:@"是否重新加载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_fileAlertView show];

    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) {
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationController popViewControllerAnimated:YES];
    }
    if (buttonIndex == 1) {
//        [self createIndicator];
        
//        [self.view removeFromSuperview];
        [self.frontView removeFromSuperview];
        [self viewDidLoad];
    }
    
    
    
    [_fileAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_fileAlertView release];
    
}

// 加载失败
- (void)fileAction
{
    
}


#pragma mark - MONActivityIndicatorViewDelegate Methods

- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView
      circleBackgroundColorAtIndex:(NSUInteger)index {
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    CGFloat alpha = 1.0f;
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

#pragma mark - 设置navigationBar的配置
- (void)createNavBar
{
    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.navigationItem.title = @"详情页面";
    //    self.navigationController.navigationBar.translucent = NO;
    // 禁止手势
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self createRightBarButton];
}

- (void)viewWillCome
{
    if (self.vegetableMenuModel.vegetable_id != nil) {
        NSDictionary *dic = @{@"vegetable_id":self.vegetableMenuModel.vegetable_id, @"phonetype":@"2", @"user_id":@"", @"is_traditional":@"0"};
        __block DetailController *deta = self;
        [MyConnection connectWithUrl:VegetableMenuURL parmaters:dic finishBlock:^(NSData *data) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = dataDic[@"data"];
            NSDictionary *dDic = [array lastObject];
            VegetableMenu *model = [VegetableMenu vegetableMenuWithVegetable_id:dDic[@"vegetable_id"] name:dDic[@"name"] fittingRestriction:dDic[@"fittingRestriction"] englishName:dDic[@"englishName"] imagePathLandscape:dDic[@"imagePathLandscape"] clickCount:dDic[@"clickCount"] materialVideoPath:dDic[@"materialVideoPath"]productionProcessPath:dDic[@"productionProcessPath"]];
            deta.vegetableMenuModel = model;
            // 视频相关
            [deta getVideo];
            
            // 创建tableview
            [deta createTableView];
            
            // 进行网络请求拿到做法这个页面的数据
            [deta startConnect];
            
        }];
    }
    else {
        // 视频相关
        [self getVideo];
        
        // 创建tableview
        [self createTableView];
        
        // 进行网络请求拿到做法这个页面的数据
        [self startConnect];
    }
}



#pragma mark - 创建tableView
- (void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    [_tableView registerClass:[MaterialTableViewCell class] forCellReuseIdentifier:@"materCell"];
    [_tableView registerClass:[CookMethodTableViewCell class] forCellReuseIdentifier:@"cookCell"];
    
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.allowsSelection = NO;
    
    // 设置headerView
    self.navigationItem.title = _vegetableMenuModel.name;
    _tableView.tableHeaderView = _tableHeaderView;
    [self.view addSubview:_tableView];
    
    [_tableView release];
    
}

#pragma mark - 实现tabelView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.sectionView == nil) {
    self.sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, headerViewHigth)] autorelease];
    _sectionView.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:100 / 255.0 blue:0 / 255.0 alpha:1.0f];
    
        // 添加材料等按钮
        for (int i = 0; i < [self.dButtonArray count]; i++) {
            
            TableHeaderlButton *materialButton = [[TableHeaderlButton alloc] initWithFrame:CGRectMake(20 + i * (self.view.frame.size.width / 4), 0, self.view.frame.size.width / 4, headerViewHigth)];
            materialButton.tag = 1000 + i;
            // 默认选择第一个界面
            if (materialButton.tag == 1000) {
                materialButton.selected = YES;
            }
            [materialButton addTarget:self action:@selector(materialButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [_sectionView addSubview:materialButton];
            
            
            // 把4个按钮添加到数组中
            [self.dBArray addObject:materialButton];
            [materialButton release];
}
        // 给材料按钮附图片和汉字
        [self setImageToMaterialButton];
    
    }
    return self.sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return headerViewHigth;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}
//
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
    
}
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //
    id str = [_tableArray objectAtIndex:indexPath.row];
    
    
    NSLog(@"%ld", (long)indexPath.row);
    
    // 材料界面判断:
    if ([str isKindOfClass:[NSString class]]) {
        MaterialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"materCell"];
        if (cell != nil) {
            cell = [[MaterialTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"materCell"];
        }
        
        if ([str hasPrefix:@"http"]) { // 如果是图片调用这个方法
            NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            [cell.materialImage sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:image];
        }
        else {
            cell.materialLabel.text = str;
            NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:18.0f]};
            CGRect rect = [str boundingRectWithSize:CGSizeMake(self.view.frame.size.width - cell.materialLabel.frame.origin.x * 2, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            cell.materialLabel.frame = CGRectMake(cell.materialLabel.frame.origin.x, cell.materialLabel.frame.origin.y, rect.size.width, rect.size.height + 50);
            cell.frame = cell.materialLabel.frame;
        }
        return (UITableViewCell *) cell;
    }
    
    // 材料界面的材米油盐.
    if ([str isKindOfClass:[DMtril class]]) {
        MaterialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"materCell"];
        if (cell != nil) {
            cell = [[MaterialTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"materCell"] ;
        }

        DMtril *dm = (DMtril *)str;
        [cell.materialLabelView.dMLabel setText:dm.dMName];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        [cell.materialLabelView.dMImageView sd_setImageWithURL:[NSURL URLWithString:dm.dMImagePath] placeholderImage:image];
        
        
        return (UITableViewCell *) cell;
    }
    
    // 判断做法界面cell
    if ([str isKindOfClass:[CookMethod class]]) {
        CookMethodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cookCell"];
        
        CookMethod *cook = (CookMethod *)str;
        
        cell.backView.backgroundColor = [UIColor whiteColor];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        [cell.cookImageView sd_setImageWithURL:[NSURL URLWithString:cook.imagePathCook] placeholderImage:image];
        [cell.cookMethodLabel setText:cook.describe];
        [cell.numLabel setText:cook.order_id];
        
        return (UITableViewCell *) cell;
    }
    
    
    
    
    
    return [[[UITableViewCell alloc] init] autorelease];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *my = (NSIndexPath *)[[tableView indexPathsForVisibleRows] firstObject];
    if (indexPath.row == my.row) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"frontView" object:nil];
    }
}





#pragma mark - 材料按钮
- (void)setImageToMaterialButton
{
    for (int i = 0; i < [self.dButtonArray count]; i++) {
        NSDictionary *dic = [self.dButtonArray objectAtIndex:i];
        NSString *imageName = dic[@"imageName"];
        NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"png"];
        NSString *imageName2 = [NSString stringWithFormat:@"%@%d", imageName, 2];
        NSString *path2 = [[NSBundle mainBundle] pathForResource:imageName2 ofType:@"png"];
        TableHeaderlButton *button = [self.dBArray objectAtIndex:i];
        if (!button.selected) {
        [button.headerImageView setImage:[UIImage imageWithContentsOfFile:path]];
        }
        else {
            [button.headerImageView setImage:[UIImage imageWithContentsOfFile:path2]];
        }
        button.headerLabel.text = dic[@"name"];
    }
}

// 材料按钮点击事件
- (void)materialButtonClick:(TableHeaderlButton *)button
{
    // 改变材料按钮外观
    [button.headerImageView setImage:nil];
    for (TableHeaderlButton *button in self.dBArray) {
        button.selected = NO;
    }
    button.selected = YES;
    [self setImageToMaterialButton];
    
    // 改变数据源
    if (button.tag == 1000) { // 底下table数据换成材料的
        [self getMaterial];
        [_tableView reloadData];
    }
    
    if (button.tag == 1001) {
        [_tableArray removeAllObjects];
        for (CookMethod *model in _detailModel.cookMethodArray) {
            
            [_tableArray addObject:model];
        }
        
        [_tableView reloadData];
    }
    
    if (button.tag == 1002) {
        [_tableArray removeAllObjects];
        [_tableArray addObjectsFromArray:self.knowArray];
        [_tableView reloadData];
        
    }
    
    if (button.tag == 1003) {
        [self downLoadVideo];
        [_tableView reloadData];
    }
}

#pragma mark - 下载视频
- (void)downLoadVideo
{
    // 开始下载
    DownLoad *down = [[DownLoad alloc] init];
    // download类下载完自己release
    
    NSString *videoPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    videoPath = [NSString stringWithFormat:@"%@/%@", videoPath, @"video"];
    
    [down downloadFileURL:self.videoArray savePath:videoPath num:0 imageURL:_vegetableMenuModel.imagePathLandscape vegetableName:_vegetableMenuModel.name];
}



#pragma mark - 进行网络请求数据
- (void)startConnect
{
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.vegetableMenuModel.vegetable_id, @"vegetable_id", @"1", @"type", @"0", @"phonetype", @"0", @"is_traditional", nil];
    
    // 防止循环拥有, 谁都释放不掉
    __block VegetableDetail *_detailModelb = self.detailModel;
    __block DetailController *con = self;
    __block NSMutableArray *knowArrayb = self.knowArray;
    
    [MyConnection connectWithUrl:DetailURL parmaters:dic1 finishBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"data"];
        for (NSDictionary *dataDic in dataArray) {
            _detailModelb.vegetable_id = dataDic[@"vegetable_id"];
            _detailModelb.imagePathMaterial = dataDic[@"imagePath"];
            
            NSArray *TblSeasoningArray = dataDic[@"TblSeasoning"];
            if ([TblSeasoningArray count] != 0) {
                for (NSDictionary *tDic in TblSeasoningArray) {
                    DMtril *model = [[DMtril alloc] init];
                    model.DMName = tDic[@"name"];
                    model.DMImagePath = tDic[@"imagePath"];
                    [_detailModelb.imagePathDMArray addObject:model];
                    [model release];
                }
            }
        }
       
        [dic1 setValue:@"2" forKey:@"type"];
        [MyConnection connectWithUrl:DetailURL parmaters:dic1 finishBlock:^(NSData *data) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *dataArray = dic[@"data"];
            for (NSDictionary *numDic in dataArray) {
                CookMethod *cookModel = [[CookMethod alloc] init];
                cookModel.order_id = numDic[@"order_id"];
                cookModel.describe = numDic[@"describe"];
                cookModel.imagePathCook = numDic[@"imagePath"];
                
                [_detailModelb.cookMethodArray addObject:cookModel];
                [cookModel release];
            }
            // 常识介绍
            [dic1 setValue:@"4" forKey:@"type"];
            [MyConnection connectWithUrl:DetailURL parmaters:dic1 finishBlock:^(NSData *data) {
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSArray *dataArray = dic[@"data"];
                NSDictionary *dDic = [dataArray objectAtIndex:0];
                _detailModelb.nutritionAnalysis = dDic[@"nutritionAnalysis"];
                _detailModelb.productionDirection = dDic[@"productionDirection"];
                _detailModelb.materialImagePath = dDic[@"imagePath"];
                
                //        [knowArrayb addObject:@"常识"]; // 用于标识, 在cell的时候选取不同的重用池
                [knowArrayb addObject: _detailModelb.materialImagePath];
                [knowArrayb addObject:[NSString stringWithFormat:@"%@: \n%@", @"常识",_detailModelb.nutritionAnalysis]];
                [knowArrayb addObject:[NSString stringWithFormat:@"%@: \n%@", @"制作指导",_detailModelb.productionDirection]];
                // 封装材料界面的数据
                [con getMaterial];
                
               
            }];
        }];
    }];
    
    
}

#pragma mark - 封装材料界面数据
- (void)getMaterial
{
    
    if ([_materialArray count] == 0) {
        NSString *s1 = [NSString stringWithFormat:@"%@: \n%@", @"原料", _vegetableMenuModel.fittingRestriction]; // 上个页面传递过来
        NSString *s2 = _detailModel.imagePathMaterial; // 材料网络请求
        NSString *s3 = [NSString stringWithFormat:@"%@: \n%@", @"材料", _vegetableMenuModel.fittingRestriction]; // 从点击界面传递过来
        NSArray *s4 = _detailModel.imagePathDMArray; // 拿到材料图片(材料网络请求)
        
        [_materialArray addObject:s1];
        
        [_materialArray addObject:s2];
        
        if (s3 != nil) {
            [_materialArray addObject:s3];
        }
        if (s4 != nil) {
            [_materialArray addObjectsFromArray:s4];
        }
    }
    
    [_tableArray removeAllObjects];
    for (id mt in _materialArray) {
        [_tableArray addObject:mt];
    }
    [_tableView reloadData];
    
}

#pragma mark - 创建播放器等有关信息

- (void)getVideo
{
    // 准备视频播放网址
    [self createMoviePlayerVideoArray];
    
    // 创建播放器
    [self createMoviePlayer];
    
    // 注册通知
    [self addNotification];
}

// 准备视频播放网址数组
- (void)createMoviePlayerVideoArray
{
    NSString *str = _vegetableMenuModel.materialVideoPath;
    NSString *str2 = _vegetableMenuModel.productionProcessPath;
    [self.videoArray addObject:str];
    [self.videoArray addObject:str2];
}

- (void)createMoviePlayer
{
    // 获得网址
    NSURL *url = [self getNetWorkURL];
    
    // 创建headerView
    _tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)] autorelease];
    [self.view addSubview:_tableHeaderView];
    
    self.moviePlayer = [[MyMoviePlayerController alloc] initWithContentURL:url];
    self.moviePlayer.view.frame = CGRectMake(0, 0, self.view.frame.size.width, _tableHeaderView.frame.size.height - buttonViewHigth);
    self.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [_tableHeaderView addSubview:_moviePlayer.view];
    [self.moviePlayer release];
//    [self.moviePlayer setFullscreen:NO];
    
    // 创建播放器上的图片
    [self createVegetableBackImage];
    
    // 创建播放按钮
    [self createPlayButton];
    
    // 创建选集按钮
    [self createCountButton];
}

// 添加播放器状态通知
- (void)addNotification
{
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    
    [notiCenter addObserver:self selector:@selector(playBackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
//    [notiCenter addObserver:self selector:@selector(moviePlayFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
//    [notiCenter addObserver:self selector:@selector(willFull:) name:MPMoviePlayerWillEnterFullscreenNotification object:self.moviePlayer];
}

//- (void)willFull:(NSNotification *)noti
//{
//    _moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
//    _moviePlayer.view.transform = CGAffineTransformConcat(_moviePlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));
//    [_moviePlayer.view setFrame: self.view.bounds];
    
//    [self.moviePlayer setFullscreen:NO];
    
//    DetailMoviePlayer *detaile = [[DetailMoviePlayer alloc] init];
//    [self.moviePlayer pause];
//    [self.navigationController pushViewController:detaile animated:YES];
//    [detaile release];

//}


//-(void)moviePlayFinish:(NSNotification *)notification{
//  
//}

-(void)playBackStateChange:(NSNotification *)notification{
    //    NSLog(@"..%ld", self.moviePlayer.playbackState);
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放...");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        case MPMoviePlaybackStateInterrupted:
            NSLog(@"快进");
            break;
        default:
            break;
    }
}


// 以下是让视频全屏时候可以根据屏幕的旋转改变
// 支持设备自动旋转
-(BOOL)shouldAutorotate{
    return NO;
}
-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    
    return UIInterfaceOrientationPortrait;
}



// 创建播放按钮
- (void)createPlayButton
{
    self.playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    _playButton.center = _moviePlayer.view.center;
    self.playButton.backgroundColor = [UIColor whiteColor];
    self.playButton.layer.cornerRadius = 25.0f;
    self.playButton.alpha = 0.7f;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"play" ofType:@"png"];
    [self.playButton setImage:[UIImage imageWithContentsOfFile:path] forState:UIControlStateNormal];
    [_playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.moviePlayer.view addSubview:self.playButton];
    [_playButton release];
}

// 播放按钮点击事件
- (void)playButtonClick:(id)sender
{
    _vegetableBackImage.hidden = YES;
    _playButton.hidden = YES;
    [_moviePlayer play];
}

// 创建播放器未播放前的图片
- (void)createVegetableBackImage
{
    self.vegetableBackImage = [[UIImageView alloc] initWithFrame:self.moviePlayer.view.frame];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [self.vegetableBackImage sd_setImageWithURL:[NSURL URLWithString:self.vegetableMenuModel.imagePathLandscape] placeholderImage:image];
    [self.moviePlayer.view addSubview:_vegetableBackImage];
    [_vegetableBackImage release];
    
}

// 获得播放器默认播放的视频(也就是视频数组中得第一个)
- (NSURL *)getNetWorkURL
{
    NSString *str = [_videoArray firstObject];
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    
    return url;
}

// 创建视频选集按钮
- (void)createCountButton
{
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, self.moviePlayer.view.frame.origin.y + self.moviePlayer.view.frame.size.height, self.view.frame.size.width, buttonViewHigth)];
    buttonView.backgroundColor = [UIColor colorWithRed:250 / 255.0 green:202 / 255.0 blue:14 / 255.0 alpha:1.0f];

    UILabel *countLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 50, 20)];
    countLabel.text = @"选集";
    countLabel.textColor = [UIColor colorWithRed:112 / 255.0 green:143 / 255.0 blue:220 / 255.0 alpha:1.0f];
    [buttonView addSubview:countLabel];
    [countLabel release];
    
    CGFloat offX = countLabel.bounds.origin.x + countLabel.frame.size.width + 10;
    CGFloat offY = 10;
    
    for (int i = 0; i < [self.videoArray count]; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(offX, offY, 40, 40)];
        [button setTitle:[NSString stringWithFormat:@"%d", i + 1] forState:UIControlStateNormal];
        button.tag = i + 100;
        [button addTarget:self action:@selector(detailbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.layer.borderWidth = 0.5f;
        button.layer.cornerRadius = button.frame.size.width / 2;
        offX += 60;
        [buttonView addSubview:button];
        [button release];
    }
    
    [_tableHeaderView addSubview:buttonView];
    [buttonView release];
    
}


// 选集按钮点击事件
- (void)detailbuttonClick:(UIButton *)button
{
    self.vegetableBackImage.hidden = YES;
    self.playButton.hidden = YES;
    
    [self.moviePlayer pause];
    NSInteger num = button.tag - 100;
    NSString *str = [self.videoArray objectAtIndex:num];
    NSURL *url = [NSURL URLWithString:str];
    self.moviePlayer.contentURL = url;
    [self.moviePlayer prepareToPlay];
    [self.moviePlayer play];
}


#pragma mark - 创建分享和收藏按钮

- (void)createFavoriteButtonImage
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"favorite" ofType:@"png"];
    self.favoriteImage = [UIImage imageWithContentsOfFile:path];
    
    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"favorite2" ofType:@"png"];
    self.favoriteImage2 = [UIImage imageWithContentsOfFile:path2];
}

- (void)createRightBarButton
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"share" ofType:@"png"];
   
    
//    UIImage *shareImage = [[UIImage imageWithContentsOfFile:imagePath] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    UIBarButtonItem *shareBar = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithContentsOfFile:imagePath] style:UIBarButtonItemStylePlain target:self action:@selector(buttonClick)];
    
    // 判断这个是否是收藏的
    BOOL isSame = [self checkIsSame];
    UIImage *image;
    // 选择收藏按钮显示的图片(如果没收藏过返回no)
    if (isSame) {
        image = self.favoriteImage2;
    }
    else {
        image = self.favoriteImage;
    }
    
    self.favoriteBar = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(favoriteClick)];
    self.navigationItem.rightBarButtonItems = @[shareBar, _favoriteBar];
    [shareBar release];
    [_favoriteBar release];
}

#pragma mark - 收藏按钮点击事件
- (void)favoriteClick
{
    // 检查一下 要收藏的是否已经在数据库中
    BOOL isHaveSame = [self checkIsSame];
    
    // 如果没有重复的返回NO
    if (!isHaveSame) {
        FavoriteModel *model = [FavoriteModel favoriteWithVegetableId:_vegetableMenuModel.vegetable_id imageURL:_vegetableMenuModel.imagePathLandscape vegetableName:_vegetableMenuModel.name];
        BOOL isSuccess = [FavoriteDataBase insertWithModel:model];
        if (isSuccess) {
            _favoriteView = [[UIAlertView alloc] initWithTitle:@"收藏成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [_favoriteView show];
            _favoriteTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(favoriteChange) userInfo:nil repeats:YES];
            [self.favoriteBar setImage:self.favoriteImage2];
        }
    }
    else {
        [FavoriteDataBase deleteWithTable:self.vegetableMenuModel.vegetable_id];
        
        _favoriteView = [[UIAlertView alloc] initWithTitle:@"已取消收藏" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
        [_favoriteView show];
        _favoriteTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(favoriteChange) userInfo:nil repeats:YES];
            [self.favoriteBar setImage:self.favoriteImage];
    }
    
}

- (void)favoriteChange
{
    [_favoriteTimer invalidate];
    [_favoriteView dismissWithClickedButtonIndex:0 animated:YES];
    [_favoriteView release];
   
}

- (BOOL)checkIsSame
{
    FavoriteModel *model = [FavoriteDataBase searchWithId:self.vegetableMenuModel.vegetable_id];
    
    if (model == nil) {
        return NO;
    }
    
    return YES;
}

#pragma mark - 分享按钮点击事件
- (void)buttonClick
{
    [self.moviePlayer pause];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_vegetableMenuModel.imagePathLandscape]];
    UIImage *image = [UIImage imageWithData:data];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"552f7daafd98c59a88000aae" shareText:_vegetableMenuModel.name shareImage:image shareToSnsNames:@[UMShareToSina] delegate:self];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_favoriteView dismissWithClickedButtonIndex:0 animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
